﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using TreeViewForXamarin.Models;

namespace TreeViewForXamarin.Adapters
{
    /// <summary>
    /// 树适配器
    /// </summary>
    public class RecyclerTreeListAdapter : RecyclerView.Adapter
    {
        #region # 变量
        private Context _actcityContext;
        private List<TreeNode> _allTreeNodes;
        private List<TreeNode> _treeNodes;//当前展示的节点
        public event EventHandler<TreeNode> SelecteItemChanged;
        #endregion

        #region # 构造器
        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="context">页面</param>
        /// <param name="treeNodes">所有的树节点</param>
        public RecyclerTreeListAdapter(Context context, List<TreeNode> allTreeNodes)
        {
            this._actcityContext = context;
            this._allTreeNodes = allTreeNodes == null ? new List<TreeNode>() : allTreeNodes;
            this._treeNodes = this._allTreeNodes.Where(x => x.IsRoot).ToList();
        }
        #endregion


        #region # 树节点点击事件——void OnItemClick(int position)
        /// <summary>
        /// 树节点点击事件
        /// </summary>
        /// <param name="position">节点位置</param>
        private void OnItemClick(int position)
        {
            TreeNode treeNode = this._treeNodes[position];//获取当前点击节点
            if (treeNode == null) return;
            if (this.SelecteItemChanged != null)
            {
                foreach (var item in this._treeNodes)
                {
                    if (item.IsSelected)
                    {
                        this.NotifyItemChanged(this._treeNodes.IndexOf(item));
                    }
                    item.IsSelected = false;
                }
                treeNode.IsSelected = true;
                this.NotifyItemChanged(position);
                this.SelecteItemChanged(this, treeNode);
            }
            if (!treeNode.HasChildNode) return;

            treeNode.IsExpanded = !treeNode.IsExpanded;//展开节点
            if (treeNode.IsExpanded)
            {
                List<TreeNode> subTreeNodes = this._allTreeNodes.Where(x => x.Parent != null && x.Parent.Data == treeNode.Data).ToList();
                this._treeNodes.InsertRange(position + 1, subTreeNodes);
                this.NotifyItemRangeInserted(position + 1, subTreeNodes.Count);
            }
            else 
            {
                List<TreeNode> subTreeNodes = this._allTreeNodes.Where(x => x.Parent != null && x.Parent.Data == treeNode.Data).ToList();

                int exandedChildCount = this.GetExandedChildCount(subTreeNodes);
                this._treeNodes.RemoveRange(position + 1, exandedChildCount);
                this.NotifyItemRangeRemoved(position + 1, exandedChildCount);
            }
        } 
        #endregion

        #region # 获取展开的子节点数量——int GetExandedChildCount(List<TreeNode> subTreeNodes)
        /// <summary>
        /// 获取展开的子节点数量
        /// </summary>
        /// <param name="subTreeNodes">子节点</param>
        /// <returns></returns>
        private int GetExandedChildCount(List<TreeNode> subTreeNodes)
        {
            int exandedChildCount = subTreeNodes.Count;
            foreach (var treeNode in subTreeNodes)
            {
                if (treeNode.IsExpanded)
                {
                    exandedChildCount += this.GetExandedChildCount(treeNode.ChildTreeNodes);
                }
                treeNode.IsExpanded = false;
            }
            return exandedChildCount;
        }
        #endregion

        #region # 创建项ViewHolder——RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        /// <summary>
        /// 创建项ViewHolder
        /// </summary>
        /// <returns></returns>
        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            View view = LayoutInflater.From(this._actcityContext).Inflate(Resource.Layout.TreeListViewContent, parent, false);
            return new TreeListViewContentHolder(view, this.OnItemClick);//自定义Holder
        }
        #endregion

        #region # 绑定ViewHolder绘制节点展示样式——void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        /// <summary>
        /// 绑定ViewHolder绘制节点展示样式
        /// </summary>
        /// <param name="holder"></param>
        /// <param name="position"></param>
        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            TreeNode treeNode = this._treeNodes[position];//获取当前点击节点

            TreeListViewContentHolder treeListViewContentHolder = holder as TreeListViewContentHolder;
            if (treeListViewContentHolder == null) return;

            treeListViewContentHolder.TextContent.Text = treeNode.TreeNodeName;//设置节点显示文本
            treeListViewContentHolder.ItemView.SetBackgroundColor(Color.Transparent);//设置节点背景色为透明
            if (treeNode.IsSelected)
            {
                //设置选中节点背景色
                treeListViewContentHolder.ItemView.SetBackgroundColor(Color.Yellow);
            }
            if (treeNode.IsExpanded)
            {
                //节点展开显示的图标
                treeListViewContentHolder.ImageIcon.SetImageResource(Resource.Drawable.expanded);
            }
            else
            {
                //节点未展开显示的图标
                treeListViewContentHolder.ImageIcon.SetImageResource(Resource.Drawable.expand);
            }

            if (treeNode.HasChildNode)
            {
                //存在子节点，设置展开节点图标显示
                treeListViewContentHolder.ImageIcon.Visibility = ViewStates.Visible;
            }
            //根据层级设置节点左边距
            treeListViewContentHolder.ItemView.SetPadding((45 * treeNode.GetLevel()), 0, 0, 0);
        }
        #endregion

        #region 显示节点的总数——int ItemCount
        /// <summary>
        /// 显示节点的总数
        /// </summary>
        public override int ItemCount { get { return this._treeNodes?.Count ?? 0; } }
        #endregion

        #region # 获取节点项的ViewType——int GetItemViewType(int position)
        /// <summary>
        /// 获取节点项的ViewType
        /// </summary>
        /// <param name="position">位置</param>
        /// <returns></returns>
        public override int GetItemViewType(int position)
        {
            return this._treeNodes[position].HasChildNode ? 0 : 1;//此处没有特殊标识节点显示样式，此处可以直接返回0
        } 
        #endregion
    }

    /// <summary>
    /// 树Holder
    /// </summary>
    public class TreeListViewContentHolder : RecyclerView.ViewHolder
    {
        public ImageView ImageIcon;
        public TextView TextContent;
        private Action<int> NodeOnItemClick;

        #region # 构造器
        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="itemView">节点View</param>
        /// <param name="nodeOnItemClick">节点点击事件</param>
        public TreeListViewContentHolder(View itemView, Action<int> nodeOnItemClick) : base(itemView)
        {
            this.ItemView = itemView;
            this.ImageIcon = itemView.FindViewById<ImageView>(Resource.Id.treeNodeImageIcon);
            this.TextContent = itemView.FindViewById<TextView>(Resource.Id.treeNodeTitle);
            this.NodeOnItemClick = nodeOnItemClick;
            this.ItemView.Click += ItemView_Click;
        }
        #endregion

        #region # 节点点击事件——void ItemView_Click(object sender, EventArgs e)
        /// <summary>
        /// 节点点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ItemView_Click(object sender, EventArgs e)
        {
            if (this.NodeOnItemClick == null) return;
            this.NodeOnItemClick(this.LayoutPosition);
        } 
        #endregion
    }
}